package com.kbook.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.kbook.log.LogWriter;

public class RequestLastLoggerFilter implements Filter {
	
	private static final Logger logger = Logger.getLogger("Access");
	private FilterConfig config;

	public FilterConfig getConfig() {
		return config;
	}

	public void setConfig(FilterConfig config) {
		this.config = config;
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest htpReq = (HttpServletRequest) req;
		long bef = System.currentTimeMillis();
		//logger.info("[enter] [" + "] [" + htpReq.getServerName() + "]");
		chain.doFilter(req, res);
		long aft = System.currentTimeMillis();
		
		/*System.out.println("[" + (aft - bef) + "]" + "["
				+ htpReq.getRequestURI() + "][" + req.getServerName() + "]["+htpReq.getAttribute("X-Real-IP")+"]");*/
		List<String> logParams = new ArrayList<String>();
		logParams.add((aft - bef)+"");
		logParams.add(htpReq.getRequestURI());
		logParams.add(req.getServerName());
		logParams.add(htpReq.getHeader("X-Real-IP")+"");
		logParams.add(htpReq.getHeader("user-agent"));
		logParams.add(req.getParameter("cid"));

		LogWriter.getInstance().createLog(logParams, logger);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
